<?php
class Address extends AppModel{
	var $name = "Address";
	var $hasMany = array(
		'Location' => array(
			'className' => 'Location',
			'foreignKey' => 'address_id'
		)
	);
	var $validate = array(
        'hash' => array(
            'rule' => 'isUnique',
            'message' => 'すでに登録されています'
        )
	);
	var $yahooKey = "cmOpXZWxg64H_AQe8Mak2nHEGpAAmIRlJ6WP.i_8FsxluqC0fDvPHRnuyhyRgWPq";
	var $reverseGeoCoderUrl = "http://reverse.search.olp.yahooapis.jp/OpenLocalPlatform/V1/reverseGeoCoder";
	function saveByLocation($lat, $lng){
		App::import('Core','HttpSocket');
		$sock = new HttpSocket();
		$response = $sock->get($this->reverseGeoCoderUrl,
			"appid={$this->yahooKey}&lat={$lat}&lon={$lng}");
		$data = simplexml_load_string($response);

		$address = array(
			'name' => $data->Feature->Property->Address[0],
			'hash' => md5($data->Feature->Property->Address[0])//検索のためのハッシュ値
		);
		$data = $this->findByHash($address['hash']);
		if(empty($data)){
			$data = array(
				'Address' => $address
			);
		}
		$this->set($data['Address']);
		if(!$this->exists()){
			return $this->save($address);
		}
		return false;
	}
}
?>